const { DataTypes } = require('sequelize');
const { sequelize } = require('../config/database');

const Product = sequelize.define('Product', {
  id: {
    type: DataTypes.STRING(50),
    primaryKey: true,
    allowNull: false,
    comment: '商品ID'
  },
  productName: {
    type: DataTypes.STRING(1000),
    allowNull: false,
    comment: '商品名称'
  },
  rank: {
    type: DataTypes.INTEGER,
    allowNull: true,
    comment: '排名'
  },
  priceUsd: {
    type: DataTypes.DECIMAL(10, 2),
    allowNull: true,
    comment: '价格（USD）'
  },
  price: {
    type: DataTypes.DECIMAL(10, 2),
    allowNull: true,
    comment: '价格（RMB）'
  },
  sellerName: {
    type: DataTypes.STRING(500),
    allowNull: true,
    comment: '店铺名称'
  },
  weekSoldCount: {
    type: DataTypes.INTEGER,
    allowNull: true,
    comment: '周销售量'
  },
  weekSales: {
    type: DataTypes.DECIMAL(15, 2),
    allowNull: true,
    comment: '周总销售额（RMB）'
  },
  weekSalesUsd: {
    type: DataTypes.DECIMAL(15, 2),
    allowNull: true,
    comment: '周销售额（USD）'
  },
  totalSalesUsd: {
    type: DataTypes.DECIMAL(15, 2),
    allowNull: true,
    comment: '总销售额（USD）'
  },
  totalSales: {
    type: DataTypes.DECIMAL(15, 2),
    allowNull: true,
    comment: '总销售额（RMB）'
  },
  relatedVideos: {
    type: DataTypes.INTEGER,
    allowNull: true,
    comment: '关联视频数'
  },
  relatedAuthor: {
    type: DataTypes.INTEGER,
    allowNull: true,
    comment: '关联达人数'
  }
}, {
  tableName: 't_product',
  timestamps: true,
  createdAt: 'createTime',
  updatedAt: 'updateTime',
  indexes: [
    {
      name: 'idx_product_name',
      fields: ['productName']
    },
    {
      name: 'idx_seller_name',
      fields: ['sellerName']
    },
    {
      name: 'idx_price_usd',
      fields: ['priceUsd']
    },
    {
      name: 'idx_price',
      fields: ['price']
    },
    {
      name: 'idx_week_sold_count',
      fields: ['weekSoldCount']
    },
    {
      name: 'idx_total_sales_usd',
      fields: ['totalSalesUsd']
    },
    {
      name: 'idx_rank',
      fields: ['rank']
    },
    {
      name: 'idx_create_time',
      fields: ['createTime']
    }
  ]
});

/**
 * 定义关联关系
 */
Product.associate = function (models) {
  // 一对多关联：一个商品可以有多个视频
  Product.hasMany(models.ProductVideo, {
    foreignKey: 'product_id',
    sourceKey: 'id',
    as: 'videos',
    onDelete: 'CASCADE',
    onUpdate: 'CASCADE'
  });
};

module.exports = Product;